package com.ferryc.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ferryc.commons.entity.TreeNode;
import com.ferryc.commons.service.CommonService;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.modules.sys.entity.SysDict;
import com.ferryc.modules.sys.mapper.ISysDictMapper;
import com.ferryc.modules.sys.service.ISysDictService;

/**
 * 
 * 类名: ISysDictService <br/>
 * 作用： 服务<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年11月22日 09:14:51 <br/>
 * 
 */
@Service
@Transactional(readOnly = true)
public class SysDictServiceImpl extends CommonService<SysDict> implements ISysDictService {

	@Autowired
	private ISysDictMapper sysDictMapper;

	@Override
	protected void init() {
		super.mapper = sysDictMapper;
	}

	@Override
	public List<TreeNode> selectTreeList(SysDict sysDict) {
		sysDict.setParentId(SysDict.SYSTEM_ID);
		sysDict.setStatus(GlobalConstant.YES);
		sysDict.setDelFlag(GlobalConstant.NO);
		List<SysDict> list = sysDictMapper.listByEntity(sysDict);
		return createNode(list);
	}

	private List<TreeNode> createNode(List<SysDict> dictList) {
		List<TreeNode> nodeList = new ArrayList<>();
		TreeNode treeNode = new TreeNode();
		treeNode.setId(SysDict.SYSTEM_ID);
		treeNode.setText(SysDict.SYSTEM_NAME);

		List<TreeNode> childNodeList = new ArrayList<>();
		for (Iterator iterator = dictList.iterator(); iterator.hasNext();) {
			SysDict sysDict = (SysDict) iterator.next();
			TreeNode childNode = new TreeNode();
			childNode.setId(sysDict.getId());
			childNode.setText(sysDict.getTypeName());
			childNodeList.add(childNode);
			childNode = null;
		}
		treeNode.setChildren(childNodeList);
		nodeList.add(treeNode);
		return nodeList;
	}

	@Override
	public boolean checkTypeCode(SysDict sysDict) {
		SysDict queryDict = new SysDict();
		queryDict.setStatus(StringUtil.EMPTY);
		queryDict.setDelFlag(GlobalConstant.DEL_FLAG_NORMAL);
		queryDict.setTypeCode(sysDict.getTypeCode());
		List<SysDict> list = sysDictMapper.listByEntity(queryDict);
		if (CollectionUtils.isEmpty(list)) {
			return Boolean.TRUE;
		}
		if (StringUtil.isBlank(sysDict.getId())) {
			return Boolean.FALSE;
		} else {
			if (list.size() == 1 && list.get(0).getId().equals(sysDict.getId())) {
				return Boolean.TRUE;
			}
			return Boolean.FALSE;
		}
	}

	@Override
	public boolean checkChild(SysDict sysDict) {
		SysDict queryDict = new SysDict();
		queryDict.setParentId(sysDict.getId());
		queryDict.setStatus(StringUtil.EMPTY);
		queryDict.setDelFlag(GlobalConstant.DEL_FLAG_NORMAL);
		int result = sysDictMapper.countByEntity(queryDict);
		if (result > 0) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

}